import functools
from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash

from .utils.auth import query

bp = Blueprint('auth', __name__, url_prefix='/auth')


# @bp.route('/', methods=['GET', 'POST'])
@bp.route('/admin_login', methods=['GET', 'POST'])
def admin_login():
    if request.method == 'GET':
        return render_template('auth/admin_login.html')
    else:
        adminID = request.form.get('adminID')
        password = request.form.get('password')

        sql = "select * from Administrator where adminID = '%s'" % adminID
        result = query(sql)
        print(result)

        if len(result) != 0:
            if result[0][2] == password:
                session['adminID'] = result[0][1]
                session.permanent = True
                return redirect(url_for('admin.admin'))
            else:
                return u'账号或密码错误'
        else:
            return u'不存在这个用户'


@bp.route('/employee_login', methods=['GET', 'POST'])
def employee_login():
    if request.method == 'GET':
        return render_template('auth/employee_login.html')
    else:
        empID = request.form.get('empID')
        password = request.form.get('password')

        sql = "select * from employee where empID = '%s'" % empID
        result = query(sql)
        print(result)
        if len(result) != 0:
            if result[0][4] == password:
                session['empID'] = result[0][1]
                session.permanent = True
                return redirect(url_for('employee.employee'))
            else:
                return u'账号或密码错误'
        else:
            return u'不存在这个用户'


@bp.route('/audit_login', methods=['GET', 'POST'])
def audit_login():
    if request.method == 'GET':
        return render_template('auth/audit_login.html')
    else:
        auditID = request.form.get('auditID')
        password = request.form.get('password')

        sql = "select * from audit where auditID = '%s'" % auditID
        result = query(sql)
        print(result)
        if len(result) != 0:
            if result[0][4] == password:
                session['auditID'] = result[0][1]
                session.permanent = True
                return redirect(url_for('audit.audit'))
            else:
                return u'账号或密码错误'
        else:
            return u'不存在这个用户'
